<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ElTree, ElInput, ElDivider, ElTreeSelect, ElTag } from 'element-plus'
import {
  deleteUserApi,
  getBackShowApi,
  getOperatorListApi,
  getEnumsApi,
  getTreeSelectListApi,
  saveApi
} from '@/api/permissionsManagement/operator'
import type { DepartmentItem, DepartmentUserItem } from '@/api/department/types'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import Write from './components/Write.vue'
import Detail from './components/Detail.vue'
import { Dialog } from '@/components/Dialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  immediate: true,
  currentPageSize: 15,
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await getOperatorListApi({
      pageIndex: unref(currentPage),
      pageSize: unref(pageSize),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await deleteUserApi(unref(ids))
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'selection'
    }
  },
  {
    field: 'id',
    label: t('operator.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'cname',
    label: t('operator.cname'),
    form: {
      component: 'Input',
      formItemProps: {
        rules: [{ required: true, trigger: ['change', 'blur'], message: '请输入姓名' }]
      }
    }
  },
  {
    field: 'nickname',
    label: '昵称',
    form: {
      component: 'Input'
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'abbr',
    label: '名称缩写',
    form: {
      component: 'Input'
      // formItemProps: {
      //   rules: [{ required: true, trigger: ['change', 'blur'], message: '请输入名称缩写' }]
      // }
    },
    search: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'phone',
    label: '手机号',
    form: {
      formItemProps: {
        rules: [
          {
            required: false,
            trigger: ['change', 'blur'],
            validator: (rule: any, value: any, callback: any) => {
              if (value) {
                const reg = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/
                if (reg.test(value)) {
                  callback()
                } else {
                  callback(new Error('请输入有效的手机号'))
                }
              } else {
                // 当 value 为空时，也必须调用 callback()
                callback()
              }
            }
          }
        ]
      }
    }
  },
  {
    field: 'email',
    label: t('operator.email'),
    form: {
      component: 'Input',
      formItemProps: {
        rules: [
          {
            required: false,
            trigger: ['change', 'blur'],
            validator: (rule: any, value: any, callback: any) => {
              if (value) {
                const reg =
                  /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
                if (reg.test(value)) {
                  callback()
                } else {
                  callback(new Error('请输入有效的邮箱地址'))
                }
              } else {
                // 当 value 为空时，也必须调用 callback()
                callback()
              }
            }
          }
        ]
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'department',
    label: '部门',
    detail: {
      slots: {
        default: (data: any) => {
          return <span>{data.department_obj ? data.department_obj.name : ''}</span>
        }
      }
    },
    search: {
      hidden: true
    },
    form: {
      formItemProps: {
        rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择部门' }],
        slots: {
          default: (data: any) => {
            return (
              <ElTreeSelect
                v-model={data.department}
                nodeKey="id"
                data={departmentList.value || []}
                props={{ label: 'name', children: 'children' }}
                checkStrictly
              />
            )
          }
        }
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return data.row?.department ? data.row?.department.name : ''
        }
      }
    }
  },
  {
    field: 'roles',
    label: t('operator.role'),
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      value: [],
      // formItemProps: {
      //   rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择角色' }]
      // },
      componentProps: {
        multiple: true,
        collapseTags: true,
        maxCollapseTags: 3
      },
      optionApi: async () => {
        const res = await getEnumsApi({})
        return res.data.roles
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return data.row?.roles_txt
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return data.roles_txt
        }
      }
    }
  },
  {
    field: 'job',
    label: t('operator.job'),
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      value: [],
      // formItemProps: {
      //   rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择岗位' }]
      // },
      componentProps: {
        multiple: true,
        collapseTags: true,
        maxCollapseTags: 3
      },
      optionApi: async () => {
        const res = await getEnumsApi({})
        return res.data.jobs
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return data.row?.job_txt
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return data.job_txt
        }
      }
    }
  },
  {
    field: 'status',
    label: '状态',
    form: {
      component: 'Select',
      value: 1,
      formItemProps: {
        rules: [{ required: true, trigger: ['change', 'blur'], message: '请选择状态' }]
      },
      componentProps: {
        options: [
          {
            label: '启用',
            value: 1
          },
          {
            label: '禁用',
            value: 0
          }
        ]
      }
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <ElTag type={data.row.status === 1 ? 'success' : 'danger'}>
              {data.row.status === 1 ? '启用' : '禁用'}
            </ElTag>
          )
        }
      }
    },
    detail: {
      slots: {
        default: (data: any) => {
          return (
            <ElTag type={data.status === 1 ? 'success' : 'danger'}>
              {data.status === 1 ? '启用' : '禁用'}
            </ElTag>
          )
        }
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'create_time',
    label: t('operator.create_time'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'remark',
    label: '备注',
    form: {
      component: 'Input',
      componentProps: {
        type: 'textarea'
      }
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('action.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 240,
      slots: {
        default: (data: any) => {
          const row = data.row as DepartmentUserItem
          return (
            <>
              <BaseButton type="primary" onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (index: number, params: any) => {
  currentPage.value = 1
  searchParams.value =
    index === 2 ? { ...params, department: '' } : { ...params, department: unref(currentNodeKey) }
  if (index === 2) {
    currentNodeKey.value = ''
    currentDepartment.value = ''
    nextTick(() => {
      treeEl.value?.setCurrentKey(null)
    })
  }
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<DepartmentItem[]>([])

const fetchDepartment = async () => {
  const res = await getTreeSelectListApi()
  departmentList.value = res.data.list
}
fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: DepartmentItem) => {
  currentNodeKey.value = data.id
  currentPage.value = 1
  searchParams.value = { ...searchParams.value, department: unref(currentNodeKey) }
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<DepartmentUserItem>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)
const ids = ref<string[]>([])

const delData = async (row?: DepartmentUserItem) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: DepartmentUserItem) => v.id) || []
  delLoading.value = true

  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

const action = async (row: DepartmentUserItem, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  const resp = await getBackShowApi({ id: row.id })
  currentRow.value = resp.data
  dialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      const res = await saveApi(formData)
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('operator.departmentList') }}</div>
        <ElInput
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('operator.searchDepartment')"
          clearable
        />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'name'
        }"
        :filter-node-method="filterNode"
        @node-click="currentChange"
      >
        <template #default="{ data }">
          <div :title="data.name" class="whitespace-nowrap overflow-ellipsis overflow-hidden">
            {{ data.name }}
          </div>
        </template>
      </ElTree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="(params) => setSearchParams(2, params)"
        @search="(params) => setSearchParams(1, params)"
      />

      <div class="mb-10px">
        <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
        <BaseButton :loading="delLoading" type="danger" @click="delData()">
          {{ t('exampleDemo.del') }}
        </BaseButton>
      </div>
      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        :cell-style="() => ({ textAlign: 'center' })"
        :header-cell-style="() => ({ textAlign: 'center' })"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
<style lang="less" scoped>
:deep(.el-tooltip) {
  justify-content: center;
}
</style>
